const {
	Controller
} = require("uni-cloud-router");
const {
	success,
	fail,
	verify_token,
	build_token,
	create_uuid,
	encrypt,
	decrypt,
	isFieldExist,
	whereObj,
	isHttpMethod,
	isAdmin,
	isSuperAdmin,
	isAuthorities,

} = require('mh-utils');
//静态配置
const createConfig = require('uni-config-center')
const envCfg = createConfig({
	pluginId: 'env'
}).config()
const ossCfg = createConfig({
	pluginId: 'oss'
}).config()

module.exports = class FileRecordController extends Controller {
	//[sys:file:list, sys:file:add, sys:file:remove]
	
	//获取 OSS的 STS临时签名
	async STSToken() {
		const { ctx, service } = this;
		const dbJQL = ctx.event.dbJQL;
		var stsObj = await get_STSToken(ossCfg)
		return stsObj;
	}
	
	/**
	 * 新增
	 * @example data
	 */
	async add() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if (isHttpMethod(ctx, 'POST')) {
			if (!isAdmin(ctx) && !isSuperAdmin(ctx)) {
				if (!isAuthorities(ctx, 'sys:file:add')) {
					return fail({
						code: 1,
						message: '该用户无上传权限'
					})
				}
			}
			try {
				delete ctx.data._id;
				var result = await dbJQL.collection("mh-sys-filerecord")
					.add({
						...ctx.data,
						createUserName: (JSON.parse(ctx.auth.user)).nickname,
						"createUserId": ctx.auth.loginUserId,
						"tenantId": ctx.auth.tenantId,
					})
				if (result.id) {
					return success({
						code: 0,
						message: '操作成功'
					})
				} else {
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			} catch (e) {
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 删除
	 * @example ?_id=1111&&fileId=2222&&createUserId=3333
	 */
	async remove() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		
		if (isHttpMethod(ctx, 'DELETE')) {
			if (!isAdmin(ctx) && !isSuperAdmin(ctx)) {
				if (!isAuthorities(ctx, 'sys:file:remove')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
				if (ctx.auth.loginUserId != ctx.query.createUserId) {
					return fail({
						code: 1,
						message: '不可操作非本人数据'
					})
				}
			}
	
			try {
				var _id = ctx.query._id;
				var fileId = ctx.query.fileId;
				if (!_id || !fileId) return fail({
					code: 1,
					message: '参数无效 [_id|fileId]'
				})
				//删除
				let cRes = await uniCloud.deleteFile({fileList: [fileId]})
				if((cRes.fileList||[]).length == 0) {
					return fail({
						code: 1,
						message: `删除文件失败，请联系管理员。requestId: ${cRes.requestId}`
					})
				}
				var result = await dbJQL.collection("mh-sys-filerecord")
					.doc(_id)
					.remove()
				if (result.deleted > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				} else {
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			} catch (e) {
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 分页查询
	 */
	async page() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'GET')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:file:list')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
			}
			try{
				var where = "";
				
				// 查询条件
				var fileName = ctx.data.fileName;
				var createUserName = ctx.data.createUserName;
				
				var sort = ctx.data.sort || "createTime";
				var order = ctx.data.order || 'asc';
				if (isFieldExist(fileName)) {
					where = whereObj({where,query:`${new RegExp(fileName,'i')}.test(fileName)`});
				}
				if (isFieldExist(createUserName)) {
					where = whereObj({where,query:`${new RegExp(createUserName,'i')}.test(createUserName)`});
				}
				
				//super超管能查看所有租户的
				if(!isSuperAdmin(ctx)){
					where = whereObj({where,query:`tenantId=='${ctx.auth.tenantId}'`});
				}
				where = whereObj({where,query:`_id != null`});
				
				// 分页
				var page = ctx.data.page || 1;
				var limit = ctx.data.limit || 500;
				var result = await dbJQL.collection("mh-sys-filerecord")
					.where(`${where}`)
					.orderBy(`${sort}`, `${order}`)
					.skip((page*1 - 1) * limit)
					.limit(limit*1)
					.get({
						getCount: true
					})
				if(!result.data){
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
				return success({
					code: 0,
					data: {
						list: result.data,
						count: result.count,
					}
				})
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	

};


